import React from 'react';
import './login.styl';
import UserService from 'service/UserService.jsx';
const userService = new UserService();

import MUtil from 'util/MUtil.jsx';
const mUtil = new MUtil();


class Login extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: '',
      redirect: mUtil.getUrlParam('redirect') || '/',
    };
  }

  componentWillMount() {
    document.title = '登录-HanYi';
  }

  onInputChange(e) {
    let inputName = e.target.name,
      inputValue = e.target.value;
    this.setState({
      [inputName]: inputValue
    });
  }
  onKeyUp(e) {
    if (e.keyCode === 13) {
      this.onSubmit();
    }
  }

  onSubmit() {
    let loginInfo = {
      username: this.state.username,
      password: this.state.password
    },
      checkResult = userService.validateInput(loginInfo);
    if (checkResult.status) {
      userService
        .login(loginInfo)
        .then(res => {
          mUtil.setStorage('userInfo',res.data);
          this.props.history.push(this.state.redirect);
        })
        .catch(err => {
          // TODO 获取err下的文本提示
          mUtil.errorTips(err.msg);
        });
    } else {
      mUtil.errorTips(checkResult.msg);
    }

  }

  render() {
    return (
      <div className="col-md-4 col-md-offset-4">
        <div className="panel panel-default logging-panel">
          <div className="panel-heading">欢迎登录 - HanYi管理系统</div>
          <div className="panel-body">
            <div>
              <div className="form-group">
                <input type="email" className="form-control"
                  name="username"
                  placeholder="请输入邮箱"
                  onKeyUp={e => this.onKeyUp(e)}
                  onChange={e => this.onInputChange(e)} />
              </div>
              <div className="form-group">
                <input type="password" className="form-control"
                  name="password"
                  placeholder="请输入密码"
                  onKeyUp={e => this.onKeyUp(e)}
                  onChange={e => this.onInputChange(e)} />
              </div>
              <button
                className="btn btn-primary btn-lg btn-block"
                onClick={() => this.onSubmit()}>登录</button>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default Login;